package com.song.osclient.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2014/9/14.
 */
public class IOUtil {
    public static byte[] getBytesFromFile(File file) throws IOException {
        FileInputStream fileinputstream;
        fileinputstream = new FileInputStream(file);
        long l = file.length();
        if (l > 0x7fffffffL) {
            fileinputstream.close();
            throw new IOException((new StringBuilder("File is to large ")).append(file.getName()).toString());
        }
        byte[] data = new byte[(int) l];
        int i = 0;
        while (i < data.length) {
            int j = fileinputstream.read(data, i, data.length - i);
            if (j >= 0) {
                i += j;
            }
        }
        if (i < data.length)
            throw new IOException((new StringBuilder("Could not completely read file ")).append(file.getName()).toString());
        fileinputstream.close();
        return data;
    }

    public static void write2File(File file, byte[] data) throws IOException {
        FileOutputStream outStream = new FileOutputStream(file);
        outStream.write(data);
        outStream.flush();
        outStream.close();
    }

    public static String inputStream2String(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }

    public static void inputStream2File(InputStream ins, File file) throws IOException {
        FileUtil.createNewFile(file);
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }
}
